package comm;

import java.io.InputStream;
import java.net.Socket;
import java.util.logging.Logger;

import main.Manager;

/** Thread that keeps listening an inputStream for messages coming from the display module.
 * 
 * @author Bruno Zumba (03/10/2011)
 *
 */
public class ReceivingThread extends Thread{
	//Debugging
	private Logger logger;
	
	private Socket socket;
	private InputStream input;
	
	private boolean running;
	
	private int connWith;
	
	public ReceivingThread(Socket socket, int connWith){
		logger = Logger.getLogger("FrameWork.Manager");
		this.socket = socket;
		this.connWith = connWith;
		
		running = false;

		
		try {
			input = this.socket.getInputStream();
		} catch (Exception e) {
			logger.warning("Couldn't get the Input Stream for the socket.");
			logger.warning(e.getMessage());
			e.printStackTrace();
			System.exit(0);
		}

		
	}

	@Override
	public void run(){
		byte[] buffer = new byte[1000];
		int size = 0;
		
		while(running){
			try {
				System.out.println("Esperando chegar msg.");
				size = input.read(buffer);
			} catch (Exception e) {
				logger.warning("Couldn't read from the socket.");
				logger.warning(e.getMessage());
				e.printStackTrace();
				this.running = false;
			}
			
			if (size == -1){ //The socket was closed. Send the display a disconnect message
				System.out.println("socket closed. From: "+this.connWith);
				setRunning(false);
				Message msg = new Message();
				msg.createDisconnectMessage(socket.getInetAddress().getHostAddress());
				Manager.redirectMessage(msg, this.connWith);
				
			} else { //Received a message. Decode it and pass it on
				Message msg = new Message();
				msg.decodeMessage(new String(buffer, 0, size));
				System.out.println("Message arrived:\n"+msg.getMsg());
				Manager.redirectMessage(msg, this.connWith);
			}
		}
	}
	
	public void setRunning(boolean running){
		this.running = running;
	}
	public boolean getRunning(){
		return this.running;
	}
	
	public void clean(){
		if (!socket.isClosed()){
			try {
				socket.close();
				input.close();
				socket.getOutputStream().close();
			} catch (Exception e) {
			}
		}
		
	}
}
	

